/*- coding = utf-8 -*-
@Time : 2023/7/4 14:27
@Author : 管茂良
@File : index.ts
@web  : www.php-china.com
@Software: WebStorm
*/

import { h, ref, render} from "vue";
import uModal from "@/uni_modules/uview-plus/components/u-modal/u-modal.vue"

interface propsInterface{
    show:boolean,
    asyncClose?:boolean,
    content?:string,
    title?:string,
    confirmText?:string,
    cancelText?:string,
    showConfirmButton?:boolean,
    showCancelButton?:boolean,
    zoom?:boolean,
    onConfirm?:Function,
    onCancel?:Function,
    close?:Function,
}
const parentNode = document.createElement('div')
parentNode.setAttribute("id","model-style")
let options = ref<propsInterface>({
    show:false,
    asyncClose:false,
    showCancelButton:true,
    content:"",
    title:""
})

const handleModalRender = () => {
    // 创建 虚拟dom
    const boxVNode = h(uModal, {...options.value})

    // #ifdef H5 || APP-PLUS
    // 将虚拟dom渲染到 container dom 上
    render(boxVNode, parentNode)
    // #endif

    // 最后将 container 追加到 body 上
    document.body.appendChild(parentNode)
    return boxVNode;
}

let modalInstance: any

const handleModal = () => {
    const unmount = ()=>{
        document.body.removeChild(parentNode)
    }
    const show = (props: propsInterface):any=>{
        console.log(modalInstance,"modalInstancemodalInstance");
        if (modalInstance) {
            const modalVue = modalInstance.component
            // 调用上述组件中定义的open方法显示弹框
            // 注意不能使用modalVue.ctx来调用组件函数（build打包后ctx会获取不到）
            modalVue.proxy.confirmHandler();
        } else {
            return new Promise((resolve, reject)=>{
                options.value.show = true;
                options.value = Object.assign(options.value,props)
                options.value.onConfirm=()=>{
                    if(!options.value.asyncClose){
                        unmount()
                        //返回modal方法进行下一步操作
                        resolve(true)
                    }else{
                        resolve(handleModal())
                    }
                }
                options.value.onCancel=()=>{
                    unmount()
                    reject(new Error())
                }
                modalInstance = handleModalRender()
            })
        }
        // if (modalInstance) {
        //     const modalVue = modalInstance.component
        //     // 调用上述组件中定义的open方法显示弹框
        //     // 注意不能使用modalVue.ctx来调用组件函数（build打包后ctx会获取不到）
        //     modalVue.proxy.show(props);
        // } else {

        // show(options.value)
        // }
    }
    const hide = ()=>{
        options.value.show = false;
        modalInstance = handleModalRender()
        document.body.removeChild(parentNode)
    }
    return {show,hide}
}


export default handleModal
